<template>
  <el-tree-select
      :data="this.$store.state.treeData"
      :props="props"
      filterable
      placeholder="请选择组织"
      @change="handleChange"
      @node-click="treeSelectChanged"
      check-strictly
      style="min-width: 200px"
  >
    <template #default="{ node, data }">
      <div class="custom-tree-node">
        <el-icon
            class="el-tree-node__expand-icon"
            @click="handleExpandIconClick(node, data, $event)"
        >
          <component :is="node.expanded ? 'arrow-down' : 'arrow-right'"></component>
        </el-icon>
        <span class="node-label">{{ data.name }}</span>
      </div>
    </template>
  </el-tree-select>
</template>

<script>
import request from "@/utils/request.js";

export default {
  name: "OrganizationTree",
  props: {
    props: {
      type: Object,
      default: () => ({
        children: "children",
        label: "name",
        value: "id",
      }),
    },
  },
  created() {
    if (this.$store.state.treeData.length===0){
      this.getOrganization();
    }
  },
  data() {
    return {
      treeData:this.$store.state.treeData
    };
  },
  methods: {
    async getOrganization() {
      try {
        const res = await request.get("/organization/" + JSON.parse(localStorage.getItem("user")).organization);
        if (res.data) {
          this.$store.state.treeData.push(res.data);
        } else {
          this.$message.error("无数据");
        }
      } catch (error) {
        this.$message.error("获取组织失败" + error);
      }
    },
    handleChange(value) {
      this.$emit("change", value);
    },
    treeSelectChanged(data, node) {
      this.$emit("tree-select-changed", data, node);
      this.getNodeChildren(data);
    },
    async getNodeChildren(data) {
      if (data.children && data.children.length > 0) {
        return;
      }
      try {
        const res = await request.get(`/organization/findOrganizations/${data.id}`);
        if (res.data.length > 0) {
          data.children = res.data;
        }
      } catch (error) {
        this.$message.error("获取子节点数据失败：" + error);
      }
    },
    handleExpandIconClick(node, data, event) {
      this.getNodeChildren(data);
      event.stopPropagation();
      node.expanded = !node.expanded;
    },
  },
};
</script>

<style scoped>
.custom-tree-node {
  display: flex;
  align-items: center;
}
.node-label {
  flex-grow: 1;
  margin-left: 8px;
}
.el-tree-node__expand-icon {
  margin-left: 0;
  margin-right: 5px;
  cursor: pointer;
}
</style>
